<template>

  <div>
      <div class="search-term">
        <el-form :inline="true" :model="searchInfo" class="demo-form-inline">                  
          <!-- <el-form-item>
            <el-button @click="onSubmit" type="primary">查询</el-button>
          </el-form-item> -->
          <el-form-item>
            <el-button @click="openDialog" type="primary" icon="el-icon-plus">新增任务</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="openPointDialog" type="primary" icon="el-icon-plus">新增打点</el-button>
          </el-form-item>
          <!-- <el-form-item>
            <el-popover placement="top" v-model="deleteVisible" width="160">
              <p>确定要删除吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button @click="deleteVisible = false" size="mini" type="text">取消</el-button>
                  <el-button @click="onDelete" size="mini" type="primary">确定</el-button>
                </div>
              <el-button icon="el-icon-delete" size="mini" slot="reference" type="danger">批量删除</el-button>
            </el-popover>
          </el-form-item> -->
        </el-form>
      </div>
    <el-row :gutter="10">
      <!-- <el-col :span="12">
        
        <el-card>
          <div slot="header">flipped-aurora团队</div>
          <div>
            <el-row>
              <el-col :span="8" :offset="8">
                <a href="https://github.com/flipped-aurora">
                  <img
                    class="org-img dom-center"
                    src="@/assets/flipped-aurora.png"
                    alt="flipped-aurora"
                  />
                </a>
              </el-col>
            </el-row>
            <el-row style="margin-left: 40px" :gutter="20">
              <template v-for="(item, index) in members">
                <el-col :span="8" :key="index">
                  <a :href="item.html_url">
                    <img class="avatar-img" :src="item.avatar_url" />
                    <a class="author-name" style="">{{ item.login }}</a>
                  </a>
                </el-col>
              </template>
            </el-row>
          </div>
        </el-card>
      </el-col> -->


      <el-col :span="12">
        <el-card>
          <div slot="header">
            任务记录
          </div>
          <div>
            <Timeline
              :timeline-items="dataTimeline"
              :message-when-no-items="messageWhenNoItems"
              :uniqueTimeline="true"
              :unique-year="true"
              :show-day-and-month="true"
              order="desc"
              dateLocale="zh-CN"
            />
          </div>
          <!-- <el-button class="load-more" @click="loadMore" type="text">Load more</el-button> -->
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <div slot="header">
            日历板
          </div>
          <div>
            <el-calendar v-model="dateValue">
              <template
                    slot="dateCell"
                    slot-scope="{date, data}">
                      <!--自定义内容-->
                        <div>
                          <div class="calendar-day">{{ data.day.split('-').slice(2).join('-') }}</div>
                              <div v-for="item in calendarData">
                                <div v-if="(item.months).indexOf(data.day.split('-').slice(1)[0])!=-1">
                                  <div v-if="(item.days).indexOf(data.day.split('-').slice(2).join('-'))!=-1">
                                        <el-tooltip class="item" effect="dark" :content="item.things" placement="right">
                                            <div class="is-selected">{{item.things}}</div>
                                        </el-tooltip>
                                    </div>
                                  <div v-else></div>
                                </div>
                            <div v-else></div>
                          </div>
                        </div>
                </template>
            </el-calendar>
          </div>

        </el-card>
      </el-col>
    </el-row>

  <el-dialog :before-close="closeDialog" :visible.sync="dialogFormVisible" title="新增任务">
      <el-form :model="formData" label-position="right" label-width="130px">
         <el-form-item label="任务名称:">
            <el-input v-model="formData.taskName" clearable placeholder="请输入" ></el-input>
      </el-form-item>
       
         <el-form-item label="任务内容:">
            <el-input type="textarea" :rows="5" placeholder="请输入内容" v-model="formData.taskContent"></el-input>
      </el-form-item>
       
      <el-form-item label="任务Owner:">
            <el-select clearable placeholder="请选择分派给谁" v-model="formData.taskOwner">
              <el-option :key="item.label" :label="`${item.label}(${item.value})`" :value="item.label" v-for="item in userOptions"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="任务标记:">
            <el-select clearable placeholder="任务标记" v-model="formData.taskTag">
              <el-option :key="item" :label="item" :value="item" v-for="item in taskTagOptions"></el-option>
            </el-select>
      </el-form-item>
       
      <el-form-item label="任务开始时间:">
            <el-date-picker
              v-model="formData.taskBeginTime"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
      </el-form-item>
       
         <el-form-item label="任务预计结束时间:">
            <el-date-picker
              v-model="formData.taskEstimateEndTime"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
      </el-form-item>
       
       <el-form-item>
            <el-button type="primary" @click="enterDialog">立即创建</el-button>
            <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
       </el-form>
    </el-dialog>

    <!-- 新增打点 -->
    <el-dialog :before-close="closeDialog" :visible.sync="dialogFormVisiblePoint" title="新增打点">
      <el-form :model="pointFormData" label-position="right" label-width="130px">
      <el-form-item label="Point名称:">
        <el-input v-model="pointFormData.pointName" clearable placeholder="请输入" ></el-input>
      </el-form-item>

      <el-form-item label="打点时间:">
            <el-date-picker
              v-model="pointFormData.pointTime"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
      </el-form-item>       
       
       <el-form-item>
            <el-button type="primary" @click="addPoint">立即创建</el-button>
            <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
        
       </el-form>
    </el-dialog>
    
  </div>
</template>

<script>
import {
    createTaskManager,
    deleteTaskManager,
    deleteTaskManagerByIds,
    updateTaskManager,
    findTaskManager,
    getTaskManagerList
} from "@/api/taskManager";  //  此处请自行替换地址
import { formatTimeToStr } from "@/utils/date";
import infoList from "@/mixins/infoList";
import { Commits, Members } from "@/api/github";
import Timeline from "timeline-vuejs";
import {getUserList} from "@/api/user";
import {createCalendarPoint,
  deleteCalendarPointByIds,
  getCalendarPointList
} from "@/api/calendarPoint"
// import eleCalendar from 'ele-calendar'
// import 'ele-calendar/dist/vue-calendar.css'
export default {
  name: "Test",
  mixins: [infoList],
  components: {
    Timeline,
  },
  data() {
    return {
      messageWhenNoItems: "There arent commits",
      members: [],
      dataTimeline: [],
      page: 0,
      listApi: getTaskManagerList,
      dialogFormVisible: false,
      dialogFormVisiblePoint: false,
      type: "",
      deleteVisible: false,
      multipleSelection: [],
      formData: {
            taskName:"",
            taskContent:"",
            taskOwner:"",
            taskCreator:"",
            taskState:"",
            taskTag:"",
            taskBeginTime:"",
            taskEstimateEndTime:"",
            taskEndTime:"",     
      },
      userOptions:[],
      taskTagOptions: ['紧急', '普通'],
      dateValue: new Date(),
      pointFormData:{
        pointName:"",
        pointTime:""
      },
      calendarData:[],
    };
  },
  created() {
    this.initUserList();
    this.getTableData({ page:1, pageSize:9999});
    this.loadCommits();
    this.loadMembers();
    this.initPointData()
  },
  filters: {
    formatDate: function(time) {
      if (time != null && time != "") {
        var date = new Date(time);
        return formatTimeToStr(date, "yyyy-MM-dd hh:mm:ss");
      } else {
        return "";
      }
    },
    formatBoolean: function(bool) {
      if (bool != null) {
        return bool ? "是" :"否";
      } else {
        return "";
      }
    }
  },
  methods: {
    async initUserList(){
      const res =  await getUserList({ page:1, pageSize:9999});
      if(res.code == 0){
        res.data.list.forEach(element => {
          this.userOptions.push({
            "label": element.nickName,
            "value": element.userName
          })
        });
      }
    },
    async addCustomer(){
      this.$message({
        type: "success",
        message: "你好"
      })
    },
    loadMore() {
      this.$message({
        type:"info",
        message:this.page
      })
      this.page++;
      this.loadCommits();
    },
    async loadCommits() {
      const res = await getTaskManagerList(1, 9999)
      this.dataTimeline = []
      if(res.code == 0){
        res.data.list.forEach((element) =>{
          if(element.taskState == '已完成'){
            this.dataTimeline.push({
                from: new Date(element.CreatedAt),
                title: `<span style="color: #26191b"><del>【${element.taskOwner}】 ${element.taskName}</del></span>
                        <div style="float:right;"><span style="color: #CCCCCC;margin-left:20px;font-size:10">${formatTimeToStr(new Date(element.taskEstimateEndTime), "yyyy-MM-dd")}</span></div>`,
                showDayAndMonth: true,
                description: `<a style="color: #26191b;line-height:1.5;" v-on:click="addCustomer"><del>${element.taskContent}</del></a>`,
            });
          }else{
            if(element.taskTag == '紧急'){
              this.dataTimeline.push({
                  from: new Date(element.CreatedAt),
                  title: `<span style="color: #26191b;line-height:2;">【${element.taskOwner}】 ${element.taskName}</span>
                          <span class="text item" style="color:red;font-weight:bold;font-size:15px"><i class="el-icon-s-flag" style="margin-left:5px"></i></span>
                          <div style="float:right;line-height:2;"><span style="color: #CCCCCC;margin-left:20px;font-size:10">${formatTimeToStr(new Date(element.taskEstimateEndTime), "yyyy-MM-dd")}</span></div>`,
                  showDayAndMonth: true,
                  description: `<div style="clear:both"><a style="color: #26191b;line-height:1.5;" href="#">${element.taskContent}</a></div>`,
              });
            }else{
              this.dataTimeline.push({
                  from: new Date(element.CreatedAt),
                  title: `<span style="color: #26191b;line-height:2;">【${element.taskOwner}】 ${element.taskName}</span>
                          <div style="float:right;line-height:2;"><span style="color: #CCCCCC;margin-left:20px;font-size:10">${formatTimeToStr(new Date(element.taskEstimateEndTime), "yyyy-MM-dd")}</span></div>`,
                  showDayAndMonth: true,
                  description: `<div style="clear:both"><a style="color: #26191b;line-height:1.5;" href="#">${element.taskContent}</a></div>`,
              });
            }
            
          }

          
        })
      }
    },
    loadMembers() {
      Members().then(({ data }) => {
        this.members = data;
        this.members.sort();
      });
    },
    //条件搜索前端看此方法
      onSubmit() {
        this.page = 1
        this.pageSize = 10             
        this.getTableData()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      deleteRow(row){
        this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.deleteTaskManager(row);
        });
      },
      async onDelete() {
        const ids = []
        if(this.multipleSelection.length == 0){
          this.$message({
            type: 'warning',
            message: '请选择要删除的数据'
          })
          return
        }
        this.multipleSelection &&
          this.multipleSelection.map(item => {
            ids.push(item.ID)
          })
        const res = await deleteTaskManagerByIds({ ids })
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          if (this.tableData.length == ids.length) {
              this.page--;
          }
          this.deleteVisible = false
          this.getTableData()
        }
      },
    async updateTaskManager(row) {
      const res = await findTaskManager({ ID: row.ID });
      this.type = "update";
      if (res.code == 0) {
        this.formData = res.data.retaskManager;
        this.dialogFormVisible = true;
      }
    },
    closeDialog() {
      this.dialogFormVisiblePoint = false;
      this.dialogFormVisible = false;
      this.formData = {
          taskName:"",
          taskContent:"",
          taskOwner:"",
          taskCreator:"",
          taskState:"",
          taskTag:"",
          taskBeginTime:"",
          taskEstimateEndTime:"",
          taskEndTime:"",
          
      };
      this.pointFormData = {
        pointName: "",
        pointTime: ""
      }
    },
    async deleteTaskManager(row) {
      const res = await deleteTaskManager({ ID: row.ID });
      if (res.code == 0) {
        this.$message({
          type: "success",
          message: "删除成功"
        });
        if (this.tableData.length == 1) {
            this.page--;
        }
        this.getTableData();
      }
    },
    async enterDialog() {
      let res;
      switch (this.type) {
        case "create":
          res = await createTaskManager(this.formData);
          break;
        case "update":
          res = await updateTaskManager(this.formData);
          break;
        default:
          res = await createTaskManager(this.formData);
          break;
      }
      if (res.code == 0) {
        this.$message({
          type:"success",
          message:"创建成功"
        })
        this.closeDialog();
        // this.getTableData();
        // this.getTableData({ page:1, pageSize:9999});
        this.loadCommits()
      }
    },
    openDialog() {
      this.type = "create";
      this.dialogFormVisible = true;
    },
    openPointDialog(){
      this.dialogFormVisiblePoint = true
    },
    async addPoint(){
      var adate = new Date(this.pointFormData.pointTime);
      const pointData = {
        pointName: this.pointFormData.pointName,
        pointMonth: String(adate.getMonth() < 9 ? "0" + (adate.getMonth() + 1) : adate.getMonth() + 1),
        pointDay: String(adate.getDate() <= 9 ? "0" + adate.getDate() : adate.getDate()),
      }
      const res = await createCalendarPoint(pointData)
      if(res.code == 0){
        this.$message({
          type:"success",
          message:"创建成功"
        })
        this.closeDialog();
        this.initPointData()
      }
    },
    async initPointData(){
      this.calendarData = []
      const res = await getCalendarPointList()
      if(res.code == 0){
        res.data.list.forEach((element) =>{
          if(element.pointMonth != "" && element.pointDay != ""){
            this.calendarData.push({
              months: [element.pointMonth],
              days: [element.pointDay],
              things: element.pointName
            }) 
          }
        })     
      }
    }
  },
};
</script>

<style scoped>
.load-more {
  margin-left: 120px;
}

.avatar-img {
  float: left;
  height: 40px;
  width: 40px;
  border-radius: 50%;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  margin-top: 15px;
}

.org-img {
  height: 150px;
  width: 150px;
}

.author-name {
  float: left;
  line-height: 65px !important;
  margin-left: 10px;
  color: darkblue;
  line-height: 100px;
  font-family: "Lucida Sans", "Lucida Sans Regular", "Lucida Grande",
    "Lucida Sans Unicode", Geneva, Verdana, sans-serif;
}

.dom-center {
  margin-left: 50%;
  transform: translateX(-50%);
}
.calendar-day{
    /* text-align: center; */
    /* color: #202535; */
    line-height: 30px;
    /* font-size: 12px; */
}
.is-selected{
    color: #F8A535;
    font-size: 10px;
    margin-top: 5px;
}
</style>
